#!/usr/bin/env python3
"""
审计日志数据模型
"""

from datetime import datetime
from typing import Any

from sqlalchemy.orm import mapped_column, Mapped
from sqlalchemy.sql.sqltypes import Boolean, DateTime, Integer, JSON, String, Text

from app.models import Base


class AuditLog(Base):
    """系统操作审计日志表"""

    __tablename__ = "audit_logs"

    # 主键
    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)

    # 操作信息
    operator: Mapped[str] = mapped_column(String(100), nullable=False, comment="操作人")
    operation_type: Mapped[str] = mapped_column(String(50), nullable=False, comment="操作类型")
    operation_target: Mapped[str | None] = mapped_column(String(100), nullable=True, comment="操作目标")

    # 操作详情
    operation_details: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True, comment="操作详情JSON")
    ip_address: Mapped[str | None] = mapped_column(String(45), nullable=True, comment="操作IP地址")
    user_agent: Mapped[str | None] = mapped_column(String(500), nullable=True, comment="用户代理")

    # 结果信息
    success: Mapped[bool] = mapped_column(Boolean, default=True, comment="操作是否成功")
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True, comment="错误信息")

    # 时间信息
    operation_time: Mapped[datetime] = mapped_column(DateTime, default=datetime.now, comment="操作时间")

    # 关联信息
    related_visitor_id: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="关联访客ID")
    related_qrcode: Mapped[str | None] = mapped_column(String(500), nullable=True, comment="关联二维码")

    def __repr__(self) -> str:
        return f"<AuditLog(id={self.id}, operator='{self.operator}', operation_type='{self.operation_type}')>"
